<template>
  <!--密码输入-->
  <van-dialog
    v-model:show="show"
    title="请输入直播密码"
    :show-cancel-button="showCancel"
    :overlay="false"
    :confirm-button-color="'#416aea'"
    :before-close="dialogClose"
    className="common-dailog"
  >
    <van-password-input
      class="pwd-input"
      v-if="$isMobile"
      :value="inputPwd"
      :focused="showKeyboard"
      info="请输入6位数字密码"
      :length="6"
      :error-info="errorInfo"
      @focus="showKeyboard = true"
    />
    <ElPwd
      v-else
      v-model:value="inputPwd"
      :info="'请输入6位数字密码'"
      :error-info="errorInfo"
    />
  </van-dialog>
  <van-number-keyboard
    v-model="inputPwd"
    :show="showKeyboard"
    :maxlength="6"
    @blur="showKeyboard = false"
  />
</template>

<script setup>
import { ref, defineExpose } from 'vue'

import ElPwd from './el-pwd.vue'

const props = defineProps({
  password: {
    type: String,
    default: ''
  },
  showCancel: {
    type: Boolean,
    default: true
  }
})

const emits = defineEmits(['pass'])

const inputPwd = ref('')
const show = ref(false)
const showKeyboard = ref(false)

const errorInfo = ref('')

const toShowDialog = (isShow) => {
  show.value = isShow
  inputPwd.value = ''
  errorInfo.value = ''
  // 如果关闭dialog
  if (showKeyboard.value) {
    showKeyboard.value = false
  }
}

const dialogClose = (action) => {
  if (action === 'confirm') {
    return confirmPwd()
  } else {
    return true
  }
}

const confirmPwd = () => {
  if (props.password !== inputPwd.value) {
    errorInfo.value = '密码不正确'
    inputPwd.value = ''

    return false
  }
  emits('pass')
  toShowDialog(false)
  return true
}

defineExpose({
  toShowDialog
})
</script>

